import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Radio,
  Select,
  Space,
  Table,
  Tag,
  Modal,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { getChannelList } from 'api/channel';
import { getArticleListAPI, delArticleByIdAPI } from 'api/article';
import errorSrc from 'assets/error.png';
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import Channel from 'components/Channel';

const { Option } = Select;
const { RangePicker } = DatePicker;
// 准备状态字典数组
const articleStatus = [
  { id: -1, name: '全部', color: 'magenta' },
  { id: 0, name: '草稿', color: 'orange' },
  { id: 1, name: '待审核', color: 'red' },
  { id: 2, name: '审核通过', color: 'green' },
  { id: 3, name: '审核失败', color: 'cyan' },
];

export default function ArticleList() {
  // 声明state函数
  const [channelList, setChannelList] = useState([]);
  const [articleData, setArticleData] = useState({});
  // 创建对象
  const formDataRef = useRef();

  const handleSubmit = (values) => {
    console.log('values  ----->  ', values);

    let formData = { ...values };

    // 判断staus是否为-1，如果是就把status键删除,不是就正常传
    if (formData.status === -1) {
      delete formData.status;
      // 日期范围不是必选的条件，有可能为undefined
      if (formData.date) {
        // 将date转换为两个键begin_pubdate end_pubdate
        const begin_pubdate = formData.date[0]
          .startOf('day')
          .format('YYYY-MM-DD HH:mm:ss');
        const end_pubdate = formData.date[1]
          .endOf('day')
          .format('YYYY-MM-DD HH:mm:ss');
        formData.begin_pubdate = begin_pubdate;
        formData.end_pubdate = end_pubdate;
      }
      delete formData.date;
      console.log(' formData ----->  ', formData);
      // 点击筛选按钮提交时，保存表单数据到ref中
      formDataRef.current = formData;
      // 使用转换后的表单数据，调用接口查询筛选的数据
      loadArticles(formData);
    }
  };
  // 封装异步函数
  const loadChannels = async () => {
    const res = await getChannelList();
    setChannelList(res.data.channels);
  };
  // 封装异步Action
  const loadArticles = async (params) => {
    const res = await getArticleListAPI(params);
    setArticleData(res.data);
  };
  const handlePageChange = (page, pageSize) => {
    console.log(' formDataRef.current ----->  ', formDataRef.current);
    // 分页请求时，从ref中读取表单数据，带到接口参数中
    loadArticles({ page, per_page: pageSize, ...formDataRef.current });
  };
  // 删除功能
  const handleDelById = (id) => {
    // 2. 调用Modal.confirm这个方法，修改文字等内容
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章？',
      okText: '确认',
      cancelText: '取消',
      // 3. onOk是点击确定时触发的函数，记得改造我异步函数
      onOk: async () => {
        await delArticleByIdAPI(id);
        console.log('formDataRef.current  ----->  ', formDataRef.current);
        console.log('articleData.page  ----->  ', articleData.page);
        loadArticles({
          ...formDataRef.current,
          page: articleData.page,
          per_page: articleData.per_page,
        });
        message.success('删除成功', 1);
      },
    });
  };
  useEffect(() => {
    // 3. 挂载后调用
    loadChannels();
    loadArticles({});
  }, []);
  // 控制列显示
  const columns = [
    {
      // title控制每一列的表头文字显示
      title: '封面',
      // dataIndex表示取出哪个字段显示在这一列
      dataIndex: 'cover',
      // key表示唯一的列id，帮助react渲染
      // render是否负责自定义渲染
      render: (value) => {
        // 形参代表原本单元格内应该显示的值
        console.log('value  ----->  ', value);
        if (!value.images.length) {
          return <img width={150} src={errorSrc} alt="" />;
        }
        return <img width={150} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      // 使用 render 自定义渲染
      render: (value) => {
        // 根据value找到对应id、文字和颜色
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      // 🔔没有dataIndex，就要加上key
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },

    {
      title: '操作',
      key: 'action',
      render: (value, record, index) => {
        // record代表的是一行数据，将来可以根据record.id去删除一条数据
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            ></Button>
            <Button
              onClick={() => handleDelById(record.id)}
              danger
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        );
      },
    },
  ];
  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          onFinish={handleSubmit}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 使用FormItem和Select 设置label和name */}
          <Form.Item label="频道" name="channel_id">
            <Select style={{ width: 200 }}>
              {/* <Option value="jack">Jack</Option>
              <Option value="lucy">Lucy</Option> */}
              {/* 渲染列表 真实的下拉列表 */}
              {channelList.map((item) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
              <Option value="Yiminghe">yiminghe</Option>
            </Select>
          </Form.Item>
          {/* 验证还可以使用 */}
          <Form.Item label="频道2" name="channel_id2">
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            {/* 2.准备提交按钮 */}
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <Table
          // 1. 给表格设置分页配置
          pagination={{
            // 当前页
            current: articleData.page,
            // 总数据量
            total: articleData.total_count,
            position: ['bottomCenter'],
            pageSize: articleData.per_page,
            onChange: handlePageChange,
          }}
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
        />
      </Card>
    </div>
  );
}
